<template>
    <div class="app-container">
        <el-card shadow="always">
            <el-form :model="queryParams" :inline="true" label-width="100px">
                <el-form-item label="网络制式：" prop="networkType">
                    <el-select v-model="queryParams.networkType" placeholder="请选择网络制式" style="width: 240px" @change="handleNetworkTypeChange">
                        <el-option v-for="dict in nhp_network_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属区县：" prop="county">
                    <el-select v-model="queryParams.county" placeholder="请选择所属区县" clearable style="width: 240px">
                        <el-option v-for="dict in nhp_county_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="GGI：" prop="cgi">
                    <el-input v-model="queryParams.cgi" placeholder="请输入CGI" clearable style="width: 240px" />
                </el-form-item>
                <el-form-item label="站号" prop="ENODEBID">
                    <el-input v-model="queryParams.ENODEBID" :placeholder="varPlaceholder" clearable style="width: 240px" />
                </el-form-item>
                <el-form-item label="小区名称：" prop="cellName">
                    <el-input v-model="queryParams.cellName" placeholder="请输入小区名称" clearable style="width: 240px" />
                </el-form-item>
                <el-form-item label="查询日期：" prop="createTime">
                    <!-- <el-date-picker v-model="queryParams.createTime" type="date" placeholder="请选择查询时间" /> -->
                    <el-date-picker  v-model="datePicker" type="daterange" range-separator="-"  start-placeholder="开始日期" end-placeholder="结束日期" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="listQualityTable">查询</el-button>
                    <el-button @click="unsetQueryForm"><el-icon>
                            <RefreshRight />
                        </el-icon>重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card shadow="always" style="margin-top: 10px;min-height: 500px;padding-bottom: 20px;">
            <el-row>
                <el-button type="primary" icon="Download" @click="exportData">导出</el-button>
            </el-row>
            <div id="table" style="margin-top: 20px;">
                <el-table v-loading="loading" ref="qualityTable" :data="tableData" style="width: 100%" @sort-change="sortChange" @filter-change="filterChange">
                    <el-table-column prop="county" label="所属区县" width="120" align="center" fixed />
                    <el-table-column prop="cgi" label="CGI" width="200" align="center" fixed />
                    <el-table-column prop="cellName" label="小区名称" width="250" align="center" fixed />
                    <el-table-column prop="status" label="状态" width="150" align="center" fixed 
                        :filter-multiple="false"
                        :filters="[
                            { text: '正常', value: 1 },
                            { text: '数据不完整', value: 2 },
                        ] " 
                        :column-key="'status'"
                        filter-placement="bottom-end">
                   
                        <template #default="scope">
                            <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'" disable-transitions>{{scope.row.status == 1 ? "正常" : "数据不完整" }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="stationNo" label="站号" width="150" align="center">
                        <template #default="scope">
                            {{  queryParams.networkType == "5G" ? scope.row.gnodebId :  scope.row.enodebId}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="coverageScore" label="覆盖维度分数" width="120" align="center" sortable="custom"   >
                        <template #default="scope">  
                            {{ scope.row.status === 2 ? '' : scope.row.coverageScore }}  
                        </template>
                    </el-table-column>
                    <el-table-column prop="structureScore" label="结构维度分数" width="120" align="center" sortable="custom"  >
                        <template #default="scope">  
                            {{ scope.row.status === 2 ? '' : scope.row.structureScore }}  
                        </template>
                    </el-table-column>
                    <el-table-column prop="capacityScore" label="容量维度分数" width="120" align="center" sortable="custom"  >
                        <template #default="scope">  
                            {{ scope.row.status === 2 ? '' : scope.row.capacityScore }}  
                        </template>
                    </el-table-column>
                    <el-table-column prop="flowScore" label="流量维度分数" width="120" align="center" sortable="custom"  >
                        <template #default="scope">  
                            {{ scope.row.status === 2 ? '' : scope.row.flowScore }}  
                        </template>
                    </el-table-column>
                    <el-table-column prop="interferenceScore" label="干扰维度分数" width="120" align="center" sortable="custom"  >
                        <template #default="scope">  
                            {{ scope.row.status === 2 ? '' : scope.row.interferenceScore }}  
                        </template>
                    </el-table-column>
                    <el-table-column prop="performanceScore" label="性能维度分数" width="120" align="center" sortable="custom"  >
                        <template #default="scope">  
                            {{ scope.row.status === 2 ? '' : scope.row.performanceScore }}  
                        </template>
                    </el-table-column>
                    <el-table-column prop="perceptionScore" label="感知维度分数" width="120" align="center" sortable="custom"  >
                        <template #default="scope">  
                            {{ scope.row.status === 2 ? '' : scope.row.perceptionScore }}  
                        </template>
                    </el-table-column>
                    <el-table-column prop="qualityScore" label="网络质量总分" width="150" fixed="right" align="center" sortable="custom">
                        <template #default="scope">  
                            {{ scope.row.status === 2 ? '' : scope.row.qualityScore }}  
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" align="center">
                        <template #default="scope">
                            <el-button link type="primary" size="small" @click="fnOpenDialog(scope.row.cgi)">详情</el-button>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <el-empty :image-size="40" />
                    </template>
                </el-table>
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 50, 100, 200]" :small="small" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next" :total="total" @size-change="listQualityTable"
                    @current-change="listQualityTable"/>
            </div>
        </el-card>

        <el-dialog v-model="dialogTableVisible" title="详情分析" width="1400" @opened="initChart">
            <el-card class="card-box">
                <el-form :model="queryParams" ref="queryForm" :inline="true">
                    <el-form-item label="时间选择">
                      <el-date-picker
                        v-model="detailDatePicker"
                        type="daterange"
                        style="width: 350px"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        align="right"
                        @change="search"
                      ></el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="detailSearch">查询</el-button>        
                    </el-form-item>
                  </el-form>
                  <div class="card-content" style="display: flex" v-show="!showAll">
                    <div class="card-left">
                      <el-table
                        :data="detailData"
                        style="width: 100%"
                        class="tableBox"
                        max-height="500"
                        id="tableBox"
                        @row-click="handleClickChange"
                        :row-class-name="tableRowClassName"
                      >
                        <el-table-column prop="county" label="所属区县" width="120" align="center"  />
                        <el-table-column prop="cgi" label="CGI" width="150" align="center"  />
                        <el-table-column prop="cellName" label="小区名称" width="250" align="center" />
                        <el-table-column prop="createTime" label="创建时间" width="200" align="center" />
                        <!-- <el-table-column prop="stationNo" label="站号" width="120" align="center">
                            <template #default="scope">
                                {{  queryParams.networkType == "5G" ? scope.row.gnodebId :  scope.row.enodebId}}
                            </template>
                        </el-table-column> -->
                        <el-table-column prop="qualityScore" label="网络质量总分" width="120" fixed="right" align="center" />
                      </el-table>
                    </div>
                    <div class="card-right">
                      <div class="title-name">分数趋势:</div>
                      <div
                        id="chart"
                        style="width: 620px; height: 320px; margin: -10px 20px 20px 40px"
                        class=""
                        ref="chart"
                        v-show="!showAll"
                      ></div>
                      <div class="data-analyse">
                        <div class="analyse-title">数据分析：</div>
                        <div class="analyse-itemlist">
                          <div class="analyse-item">
                            <a>所选时间：{{ selectedDays }}天</a>
                          </div>
                          <div class="analyse-item">
                            <a>网络质量平均分：{{ averageScore.toFixed(2) }}分</a>
                          </div>
                          <div class="analyse-item">
                            <a>所选时间内最高分：{{ maxScore }}分</a>
                          </div>
                          <div class="analyse-item">
                            <a>所选时间内最低分:{{ minScore }}分</a>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
            </el-card>
        </el-dialog>
    </div>
</template>

<script setup name="networkQuality">
import {ref} from 'vue';
import { queryQuality4gResultList, queryQuality5gResultList , detailList } from '@/api/biz/networkQuality';
import * as XLSX from 'xlsx/xlsx.mjs';
import * as echarts from 'echarts';

const { proxy } = getCurrentInstance();

const { nhp_county_type, nhp_network_type } = proxy.useDict("nhp_county_type", "nhp_network_type");

const queryParams = ref({
    networkType: "5G",
    createTime: "",
    county:"",
    cgi:"",
    ENODEBID:"",
    cellName:""
})

var currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 1);

const varPlaceholder = ref('请输入GNODEBID')

const pickStatus = ref()
const nowSortContent = ref()
const nowOrder = ref()

const tableData = ref([])
const detailData = ref([])

const pageSize = ref(10)
const currentPage = ref(1)
const total = ref(0)

// 时间选择器(默认当天往前一周)
const datePicker = ref('');
const detailDatePicker = ref('');
const end = new Date();
const start  = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
const defaultDateRange = [new Date(), currentDate];
datePicker.value = defaultDateRange;
detailDatePicker.value = [start,end];

const nowStatus = ref()

const dialogTableVisible = ref(false)
const chooseRowCgi = ref()

const chart = ref(null);
let chartInstance = null;
const selectedDays = ref(0);
const averageScore = ref(0);
const maxScore = ref(0);
const minScore = ref(0);
const currentNetworkType = ref("5G")

// 重置
function unsetQueryForm(){
    queryParams.value={
        networkType: "5G",
        createTime: [],
        county:"",
        cgi:"",
        ENODEBID:"",
        cellName:""
    }
}

function listQualityTable() {
    const param = {};
    param.pageSize = pageSize.value;
    param.pageNum = currentPage.value;
    param.county = queryParams.value.county;
    param.cgi = queryParams.value.cgi;
    param.ENODEBID = queryParams.value.ENODEBID;
    param.cellName = queryParams.value.cellName;
    param.createStart = formatDate(datePicker.value[0]);
    param.createEnd = formatDate(datePicker.value[1]);
    param.sortContent = nowSortContent.value;
    param.order = nowOrder.value;
    param.status = nowStatus.value;
    if (queryParams.value.networkType == "5G") {
        //加载5G结果
        queryQuality5gResultList(param).then(res => {
            tableData.value = res.rows;
            total.value = res.total;
        })

    } else if (queryParams.value.networkType == "4G") {
        //加载4G结果
        queryQuality4gResultList(param).then(res => {
            tableData.value = res.rows;
            total.value = res.total;
            currentNetworkType.value = queryParams.value.networkType
        })

    }
    console.log("param : "+formatDate(datePicker.value[0]));
    console.log("typeof : "+ typeof formatDate(datePicker.value[0]));
}

// 分数排序
function sortChange(column, prop, order){
    nowSortContent.value = column.prop;
    nowOrder.value = column.order;
    console.log(nowSortContent.value , nowOrder.value);
    listQualityTable();
}

// 格式化日期
function formatDate(dateString){
    const date = new Date(dateString);  
    const year = date.getFullYear();  
    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 加 1 因为月份是从 0 开始的，并使用 padStart 来确保月份是两位数  
    const day = date.getDate().toString().padStart(2, '0'); // 使用 padStart 来确保日期是两位数  
    return `${year}-${month}-${day}`; 
}

// 筛选状态
function filterChange(filters){
    // console.log(filters.status[0]);
    nowStatus.value  = filters.status[0];
    listQualityTable();
}

// 站号的placeholder随网络制式的选择而改变
function handleNetworkTypeChange(value){
    if(value === '4G'){
        varPlaceholder.value = '请输入ENODEBID ';
    }else if(value === '5G'){
        varPlaceholder.value = '请输入GNODEBID ';
    }
}


// 打开详情页
function fnOpenDialog(rowCGI){
    dialogTableVisible.value = true;
    // console.log(rowCGI);
    chooseRowCgi.value = rowCGI;
    listDetailTable(chooseRowCgi.value);
}
// 详情页列表
function listDetailTable(rowCGI){
    const param = {};
    param.cgi = rowCGI;
    param.networkType = currentNetworkType.value;
    param.createStart = formatDate(detailDatePicker.value[0]);
    param.createEnd = formatDate(detailDatePicker.value[1]);
    detailList(param).then(res => {
        detailData.value = res.data;
    })
    drawChart();
}

function detailSearch(){
    listDetailTable(chooseRowCgi.value);
    // drawChart();
    initChart();
}

function initChart(){
    chartInstance = echarts.init(chart.value);
    drawChart();
    calculateStatistics();
}

function drawChart(){
    const xData = detailData.value.map(item => item.createTime); // 创建时间数组  
    const yData = detailData.value.map(item => item.qualityScore); // 网络质量总分数组  

    const options = {  
        tooltip: {
          trigger: "axis",
        },
        grid: {
          left: "5%",
          right: "15%",
          bottom: "10%",
        },
        xAxis: {  
            type: 'category',  
            data: xData,  
        },  
        yAxis: {  
            type: 'value',  
        },  
        series: [{  
            data: yData,  
            type: 'line',  
            smooth: true,  
        }],  
    };  
    chartInstance.setOption(options);  
}


function calculateStatistics(){
    const scores = detailData.value.map(item => item.qualityScore);  
    const startDate = new Date(detailDatePicker.value[0]);  
    const endDate = new Date(detailDatePicker.value[1]);  
    const diffTime = endDate - startDate;  
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    selectedDays.value = diffDays+1;
    averageScore.value = scores.reduce((sum, score) => sum + score, 0) / scores.length;
    maxScore.value = Math.max(...scores);  
    minScore.value = Math.min(...scores);
}

function exportData() {
    const param = {};
    param.county = queryParams.value.county;
    param.cgi = queryParams.value.cgi;
    param.ENODEBID = queryParams.value.ENODEBID;
    param.cellName = queryParams.value.cellName;
    param.createStart = formatDate(datePicker.value[0]);
    param.createEnd = formatDate(datePicker.value[1]);
    param.sortContent = nowSortContent.value;
    param.order = nowOrder.value;
    param.status = nowStatus.value;
    param.networkType = queryParams.value.networkType
    proxy.download("/networkQuality/exportQualityList", {
        ...param
    }, `网络质量_${new Date().getTime()}.xlsx`);
}

listQualityTable();

</script>

<style scoped>
.card-box {
  padding: 0px;
}
.card-left{
    width: 55%;
}
.title-name{
    justify-content: space-between;
    font-size: 14px;
    font-weight: bold;
}

.card-right{
    margin-left: 20px;
    width: 45%;
    /* border: 1px solid #000; */
}

.data-analyse {
    margin: 10px;
    height: 100px;
    width: 300px;
    .analyse-title {
      height: 50px;
      padding: 10px 10px 0px 10px;
      font-weight: bold;
      font-size: 14px;
    }
    .analyse-itemlist {
      height: 60px;
      width: 600px;
      margin-left: 50px;
      font-size: 14px;
      display: flex;
      flex-wrap: wrap;
    }
    .analyse-item {
      min-width: 300px;
      height: 30px;
      margin: 0px;
      padding: 0px;
      font-size: 15px;
    }
  }

</style>